package com.chy.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {
    public CustomMetaObjectHandler() {
    }

    @Override
    public void insertFill(MetaObject metaObject) {

        String[] setterNames = metaObject.getSetterNames();
        List<String> strings = Arrays.asList(setterNames);

        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        if(strings.contains("createUser") && strings.contains("updateUser")) {
            if (BaseContext.getCurrentId() != null) {
                metaObject.setValue("createUser", BaseContext.getCurrentId());
                metaObject.setValue("updateUser", BaseContext.getCurrentId());
            } else {
                metaObject.setValue("createUser", 0L);
                metaObject.setValue("updateUser", 0L);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String[] setterNames = metaObject.getSetterNames();
        List<String> strings = Arrays.asList(setterNames);

        metaObject.setValue("updateTime", LocalDateTime.now());
        if(strings.contains("updateUser")) {
            metaObject.setValue("updateUser", BaseContext.getCurrentId());
        }

    }
}
